package server;

import java.io.Serializable;

public class Game implements Serializable {

    private Ship[] ships = {Ship.zShip, Ship.tShip, Ship.diagonallyShip};
    private String name = null;
    private Player[] players = new Player[10];
    public int numberOfPlyers = 0;
    boolean finished = false;

    public Game(String name) {
        setName(name);
    }

    public Ship[] getShips() {
        return ships;
    }

    public String getName() {
        return name;
    }

    public int getPlayerNum(String name) {
        for (int i = 0; i < players.length; i++) {
            if (players[i] != null) {
                if (players[i].getName().equals(name)) {
                    return i;
                }
            }
        }
        return -1;

    }
    public void update()
    {
        int playerNotLosedCounter = 0; //counter for not losed players
        int playerLosedCounter = 0; //counter for not losed players
        
        for (int i = 0; i < players.length; i++) {
            if (players[i] != null) {
                if (!players[i].lose)
                     playerNotLosedCounter++;
                else
                    playerLosedCounter++;
            }
            if ( playerNotLosedCounter > 1)
                return;
        }
        if (playerLosedCounter > 0)
            finished = true;
    }
    public void setName(String name) {
        if (name != null) {
            this.name = name;
        }
    }

    public int join(Player p) {
        for (int i = 0; i < players.length; i++) {
            if (players[i] == null) {
                players[i] = p;
                numberOfPlyers++;
                return i;
            }
        }
        return -1;
    }

    public void leave(int p) {
        players[p] = null;
        numberOfPlyers--;
    }

    public String toString() {
        String s = "Game Name: " + name + "\tNumber Of Players: " + numberOfPlyers + "\n";
        int i = 0;
        for (Player p : players) {
            s += ++i + " " + (p == null ? "NULL" : p) + "\n";
        }
        return s;
    }

    public Player[] getPlayers() {
        return players;
    }

    public void setPlayers(Player[] players) {
        this.players = players;
    }
}
